from datetime import date, datetime

from django.db import transaction
from django.shortcuts import render
from django.utils.timezone import make_aware

# Create your views here.

from rest_framework import viewsets
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework import status
from rest_framework import filters
from rest_framework.views import APIView
from rest_framework.schemas import AutoSchema, coreapi
from coreapi import Field
import coreschema
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from django_filters.rest_framework import DjangoFilterBackend

from django.db.models import Q

from .serializers import *

from .models import DataActiontime, DataFaultcode, DataState, FanucAxis, Faultcontent, FanucCycle


class ActiontimeCustomSchema(AutoSchema):
    def get_manual_fields(self, path, method):
        # 获取父类中已有的手动字段
        manual_fields = super().get_manual_fields(path, method)

        if method.lower() == "get":
            # 为 GET 请求添加查询参数
            manual_fields = [
                Field(
                    name="assetnum",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="设备编号"),
                ),
                Field(
                    name="name",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="测点名称"),
                ),
                Field(
                    name="location",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="区域"),
                ),
                Field(
                    name="start_time",
                    required=True,
                    location="query",
                    schema=coreschema.String(description="开始时间2025-02-01 16:34:42"),
                ),
                Field(
                    name="end_time",
                    required=True,
                    location="query",
                    schema=coreschema.String(description="结束时间2025-02-17 16:34:42"),
                ),
                Field(name="page", required=False, location="query", schema=coreschema.String(description="第几页")),
                Field(
                    name="page_size",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="页面大小"),
                ),
            ]
        return manual_fields

class DataActiontime_ViewSet(APIView):
   # 设置默认的每页默认数据量
    page_size = 10000
    # 设置在API DOC的字段显示
    schema = ActiontimeCustomSchema()

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data_list = self.get_queryset(request)

        # 获取页码
        page = request.GET.get("page")

        # 根据URL参数可能提供的每页数据量来覆盖默认设置
        try:
            page_size = int(request.GET.get("page_size", self.page_size))
            print("页面尺寸："+str(page_size))
        except ValueError:
            page_size = self.page_size
            print(page_size)

        # 创建Paginator对象
        paginator = Paginator(data_list, page_size)  # page_size是每页显示的数量

        try:
            # 获取指定页的数据
            queryset_page = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是一个整数，展示第一页
            queryset_page = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围(例如9999)，展示最后一页
            queryset_page = paginator.page(paginator.num_pages)

        # 序列化数据
        s = DataActiontimeSerializer(instance=queryset_page, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

    def get_queryset(self, request, *args, **kwargs):
        queryset = DataActiontime.objects.filter().order_by("timestamp")
        # 获取请求的参数
        start_time_param = request.query_params.get("start_time", None)
        end_time_param = request.query_params.get("end_time", None)

        id = request.query_params.get("id")
        assetnum = request.query_params.get("station")
        location = request.query_params.get("area")
        name=request.query_params.get("item")
        print(assetnum)
        # 根据参数是否存在添加不同筛选条件
        if id is not None:
            queryset = queryset.filter(id=id)
        if assetnum is not None:
            queryset = queryset.filter(assetnum__contains=assetnum)
        if name is not None:
            queryset = queryset.filter(name=name)
        if (start_time_param and end_time_param) is not None:
            start_time_param_trans = datetime.strptime(start_time_param, "%Y-%m-%d %H:%M:%S")
            end_time_param_trans = datetime.strptime(end_time_param, "%Y-%m-%d %H:%M:%S")
            print(start_time_param_trans)
            print(end_time_param_trans)
            queryset = queryset.filter(timestamp__gte=start_time_param_trans, timestamp__lte=end_time_param_trans)
        else:
            pass

        return queryset



class DataFaultcode_ViewSet(APIView):
    page_size = 10

    schema = AutoSchema(
        manual_fields=[
            Field(
                name="start_time",
                required=True,
                location="query",
                schema=coreschema.String(description="开始时间"),
            ),
            Field(
                name="end_time",
                required=True,
                location="query",
                schema=coreschema.String(description="结束时间"),
            ),
            Field(
                name="assetnum",
                required=False,
                location="query",
                schema=coreschema.String(description="设备编号"),
            ),
        ]
    )

    def get(self, request, *args, **kwargs):
        data_faultcode_list = self.get_queryset(request)
        serializer = DataFaultcodeSerializer(data_faultcode_list, many=True)
        if data_faultcode_list:
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response("No data", status=status.HTTP_400_BAD_REQUEST)

    def get_queryset(self, request, *args, **kwargs):
        queryset = DataFaultcode.objects.all()

        # 时间范围规定不为空
        start_time_param = request.query_params.get("start_time", None)
        end_time_param = request.query_params.get("end_time", None)
        if (start_time_param and end_time_param) is None:
            queryset = DataFaultcode.objects.none()
            print("no time range")
        else:
            start_time_param_trans = make_aware(datetime.strptime(start_time_param, "%Y-%m-%d %H:%M:%S"))
            end_time_param_trans = make_aware(datetime.strptime(end_time_param, "%Y-%m-%d %H:%M:%S"))
            print(start_time_param_trans)
            print(end_time_param_trans)
            queryset = queryset.filter(timestamp__gte=start_time_param_trans, timestamp__lte=end_time_param_trans)

        # 按设备模糊查询      示例：CBM1OP20B CHM2OP120A
        assetnum = request.query_params.get("assetnum", None)
        if assetnum is not None:
            queryset = queryset.filter(Q(assetnum__icontains=assetnum))
        else:
            print("no assetnum")

        return queryset


class DataState_ViewSetCustomSchema(AutoSchema):
    def get_manual_fields(self, path, method):
        # 获取父类中已有的手动字段
        manual_fields = super().get_manual_fields(path, method)

        if method.lower() == "get":
            # 为 GET 请求添加查询参数
            manual_fields = [
                Field(
                    name="start_time",
                    required=True,
                    location="query",
                    schema=coreschema.String(description="开始时间"),
                ),
                Field(
                    name="end_time",
                    required=True,
                    location="query",
                    schema=coreschema.String(description="结束时间"),
                ),
                Field(
                    name="name",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="测点名称"),
                ),
                Field(
                    name="assetnum",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="设备编号"),
                ),
                Field(
                    name="location",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="设备所属区域"),
                ),
                Field(
                    name="tag",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="所属动作轴"),
                ),
            ]
        return manual_fields


class DataState_ViewSet(APIView):
    # 设置默认的每页默认数据量
    page_size = 10000
    # 设置在API DOC的字段显示
    schema = DataState_ViewSetCustomSchema()

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data_list = self.get_queryset(request)

        # 获取页码
        page = request.GET.get("page")

        # 根据URL参数可能提供的每页数据量来覆盖默认设置
        try:
            page_size = int(request.GET.get("page_size", self.page_size))
            print(page_size)
        except ValueError:
            page_size = self.page_size
            print(page_size)

        # 创建Paginator对象
        paginator = Paginator(data_list, page_size)  # page_size是每页显示的数量

        try:
            # 获取指定页的数据
            queryset_page = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是一个整数，展示第一页
            queryset_page = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围(例如9999)，展示最后一页
            queryset_page = paginator.page(paginator.num_pages)

        # 序列化数据
        s = DataStateSerializer(instance=queryset_page, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

    def get_queryset(self, request, *args, **kwargs):
        # 这里实现获取数据集合的逻辑
        # 例如: return Model.objects.all()
        # 创建一个基础的查询集
        # queryset = OutputLoopa.objects.using("as_manage_analysis").annotate(staion_order=F('staion')).order_by('staion_order')
        queryset = DataState.objects.filter().order_by("timestamp")
        # 获取请求的参数

        start_time_param = request.query_params.get("start_time", None)
        end_time_param = request.query_params.get("end_time", None)

        id = request.query_params.get("id")
        assetnum = request.query_params.get("assetnum")
        location = request.query_params.get("location")
        name = request.query_params.get("channel")
        print(assetnum)
        print(name)
        # 根据参数是否存在添加不同筛选条件
        if id is not None:
            queryset = queryset.filter(id=id)
        if assetnum is not None:
            queryset = queryset.filter(assetnum__contains=assetnum)
        if name is not None:
            queryset = queryset.filter(name__contains=name)
        if (start_time_param and end_time_param) is not None:
            start_time_param_trans = datetime.strptime(start_time_param, "%Y-%m-%d %H:%M:%S")
            end_time_param_trans = datetime.strptime(end_time_param, "%Y-%m-%d %H:%M:%S")
            print(start_time_param_trans)
            print(end_time_param_trans)
            queryset = queryset.filter(timestamp__gte=start_time_param_trans, timestamp__lte=end_time_param_trans)
        else:
            print("aaaaa")

        return queryset


class FanucAxis_ViewSet(APIView):
    pagesize = 10

    schema = AutoSchema(
        manual_fields=[
            Field(
                name="start_time",
                required=True,
                location="query",
                schema=coreschema.String(description="开始时间"),
            ),
            Field(
                name="end_time",
                required=True,
                location="query",
                schema=coreschema.String(description="结束时间"),
            ),
            Field(
                name="assetnum",
                required=False,
                location="query",
                schema=coreschema.String(description="设备编号"),
            ),
            Field(
                name="channel",
                required=False,
                location="query",
                schema=coreschema.String(description="测点类型"),
            ),
            Field(
                name="location",
                required=False,
                location="query",
                schema=coreschema.String(description="所属区域"),
            ),
        ]
    )

    def get(self, request, *args, **kwargs):
        fanucaxis_list = self.get_queryset(request)
        serializer = FanucAxisSerializer(fanucaxis_list, many=True)
        if fanucaxis_list:
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response("No data", status=status.HTTP_400_BAD_REQUEST)

    def get_queryset(self, request, *args, **kwargs):
        queryset = FanucAxis.objects.all()

        # 时间范围规定不为空
        start_time_param = request.query_params.get("start_time", None)
        end_time_param = request.query_params.get("end_time", None)
        if (start_time_param and end_time_param) is None:
            queryset = FanucAxis.objects.none()
            print("no time range")
        else:
            start_time_param_trans = make_aware(datetime.strptime(start_time_param, "%Y-%m-%d %H:%M:%S"))
            end_time_param_trans = make_aware(datetime.strptime(end_time_param, "%Y-%m-%d %H:%M:%S"))
            print(start_time_param_trans)
            print(end_time_param_trans)
            queryset = queryset.filter(timestamp__gte=start_time_param_trans, timestamp__lte=end_time_param_trans)

        # 按设备模糊查询      示例：CBM1OP20B CHM2OP120A
        assetnum = request.query_params.get("assetnum", None)
        if assetnum is not None:
            queryset = queryset.filter(Q(assetnum__icontains=assetnum))
        else:
            print("no assetnum")

        # 按测点类型模糊查询
        channel = request.query_params.get("channel", None)
        if channel is not None:
            queryset = queryset.filter(Q(channel__icontains=channel))
        else:
            print("no channel")

        # 按设备所属区域模糊查询
        location = request.query_params.get("location", None)
        if location is not None:
            queryset = queryset.filter(Q(location__icontains=location))
        else:
            print("no location")

        return queryset


class Faultcontent_ViewSet(APIView):
    pagesize = 10

    schema = AutoSchema(
        manual_fields=[
            Field(
                name="assetnum",
                required=False,
                location="query",
                schema=coreschema.String(description="设备编号"),
            ),
            Field(
                name="location",
                required=False,
                location="query",
                schema=coreschema.String(description="设备所属区域"),
            ),
            Field(
                name="level",
                required=False,
                location="query",
                schema=coreschema.Integer(description="报警等级"),
            ),
            Field(
                name="code",
                required=False,
                location="query",
                schema=coreschema.String(description="报警代码"),
            ),
            Field(
                name="name",
                required=False,
                location="query",
                schema=coreschema.String(description="报警点位"),
            ),
            Field(
                name="description",
                required=False,
                location="query",
                schema=coreschema.String(description="报警描述"),
            ),
            Field(
                name="remark",
                required=False,
                location="query",
                schema=coreschema.String(description="备注"),
            ),
        ]
    )

    def get(self, request, *args, **kwargs):
        faultcontent_list = self.get_queryset(request)
        serializer = FaultcontentSerializer(faultcontent_list, many=True)
        if faultcontent_list:
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response("No data", status=status.HTTP_400_BAD_REQUEST)

    def get_queryset(self, request, *args, **kwargs):
        queryset = Faultcontent.objects.all()

        # 按设备编号模糊查询
        assetnum = request.query_params.get("assetnum", None)
        if assetnum is not None:
            queryset = queryset.filter(Q(assetnum__icontains=assetnum))
        else:
            print("no assetnum")

        # 按设备所属区域模糊查询
        location = request.query_params.get("location", None)
        if location is not None:
            queryset = queryset.filter(Q(location__icontains=location))
        else:
            print("no location")

        # 按报警等级精确查询
        level = request.query_params.get("level", None)
        if level is not None:
            queryset = queryset.filter(Q(level__exact=level))
        else:
            print("no level")

        # 按报警代码模糊查询
        code = request.query_params.get("code", None)
        if code is not None:
            queryset = queryset.filter(Q(code__icontains=code))
        else:
            print("no code")

        # 按报警点位模糊查询
        name = request.query_params.get("name", None)
        if name is not None:
            queryset = queryset.filter(Q(name__icontains=name))
        else:
            print("no name")

        # 按报警描述模糊查询
        description = request.query_params.get("description", None)
        if description is not None:
            queryset = queryset.filter(Q(description__icontains=description))
        else:
            print("no description")

        # 按备注模糊查询
        remark = request.query_params.get("remark", None)
        if remark is not None:
            queryset = queryset.filter(Q(remark__icontains=remark))
        else:
            print("no remark")

        return queryset


class FanucCycle_ViewSetCustomSchema(AutoSchema):
    def get_manual_fields(self, path, method):
        # 获取父类中已有的手动字段
        manual_fields = super().get_manual_fields(path, method)

        if method.lower() == "get":
            # 为 GET 请求添加查询参数
            manual_fields = [
                Field(
                    name="start_time",
                    required=True,
                    location="query",
                    schema=coreschema.String(description="开始时间"),
                ),
                Field(
                    name="end_time",
                    required=True,
                    location="query",
                    schema=coreschema.String(description="结束时间"),
                ),
                Field(
                    name="assetnum",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="设备编号"),
                ),
                Field(
                    name="location",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="所属区域"),
                ),
            ]
        return manual_fields


class FanucCycle_ViewSet(APIView):
    # 设置默认的每页默认数据量
    page_size = 10000
    # 设置在API DOC的字段显示
    schema = FanucCycle_ViewSetCustomSchema()

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data_list = self.get_queryset(request)

        # 获取页码
        page = request.GET.get("page")

        # 根据URL参数可能提供的每页数据量来覆盖默认设置
        try:
            page_size = int(request.GET.get("page_size", self.page_size))
            print(page_size)
        except ValueError:
            page_size = self.page_size
            print(page_size)

        # 创建Paginator对象
        paginator = Paginator(data_list, page_size)  # page_size是每页显示的数量

        try:
            # 获取指定页的数据
            queryset_page = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是一个整数，展示第一页
            queryset_page = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围(例如9999)，展示最后一页
            queryset_page = paginator.page(paginator.num_pages)

        # 序列化数据
        s = FanucCycleSerializer(instance=queryset_page, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

    def get_queryset(self, request, *args, **kwargs):
        # 这里实现获取数据集合的逻辑
        # 例如: return Model.objects.all()
        # 创建一个基础的查询集
        # queryset = OutputLoopa.objects.using("as_manage_analysis").annotate(staion_order=F('staion')).order_by('staion_order')
        queryset = FanucCycle.objects.filter().order_by("timestamp")
        # 获取请求的参数

        start_time_param = request.query_params.get("start_time", None)
        end_time_param = request.query_params.get("end_time", None)

        id = request.query_params.get("id")
        assetnum = request.query_params.get("assetnum")
        location = request.query_params.get("location")
        print(assetnum)
        # 根据参数是否存在添加不同筛选条件
        if id is not None:
            queryset = queryset.filter(id=id)
        if assetnum is not None:
            queryset = queryset.filter(assetnum__contains=assetnum)
        if location is not None:
            queryset = queryset.filter(location__contains=location)
        if (start_time_param and end_time_param) is not None:
            start_time_param_trans = datetime.strptime(start_time_param, "%Y-%m-%d %H:%M:%S")
            end_time_param_trans = datetime.strptime(end_time_param, "%Y-%m-%d %H:%M:%S")
            print(start_time_param_trans)
            print(end_time_param_trans)
            queryset = queryset.filter(timestamp__gte=start_time_param_trans, timestamp__lte=end_time_param_trans)
        else:
            print("aaaaa")

        return queryset


